﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 设计模块.Observer
{
    #region Observer
    // "Subject"
    public abstract class Subject
    {
        // Fields
        private ArrayList observers = new ArrayList();

        // Methods
        public void Attach(Observer observer)
        {
            observers.Add(observer);
        }

        public void Detach(Observer observer)
        {
            observers.Remove(observer);
        }

        public void Notify()
        {
            foreach (Observer o in observers)
                o.Update();
        }
    }

    // "ConcreteSubject"
    public class ConcreteSubject : Subject
    {
        // Fields
        private string subjectState;

        // Properties
        public string SubjectState
        {
            get { return subjectState; }
            set { subjectState = value; }
        }
    }

    // "Observer"
    public abstract class Observer
    {
        // Methods
        abstract public void Update();
    }

    // "ConcreteObserver"
    public class ConcreteObserver : Observer
    {
        // Fields
        private string name;
        private string observerState;
        private ConcreteSubject subject;

        // Constructors
        public ConcreteObserver(ConcreteSubject subject,
          string name)
        {
            this.subject = subject;
            this.name = name;
        }

        // Methods
        override public void Update()
        {
            observerState = subject.SubjectState;
            Console.WriteLine("Observer {0}'s new state is {1}",
              name, observerState);
        }

        // Properties
        public ConcreteSubject Subject
        {
            get { return subject; }
            set { subject = value; }
        }
    }

    #endregion
}
